// mv_crawler.js
import axios from 'axios';
import mysql from 'mysql2/promise';
const cheerio = require('cheerio');


// 数据库配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'musiccenter',
  charset: 'utf8mb4'
};

// QQ音乐MV页面URL
const PAGE_URL = 'https://y.qq.com/n/ryqq/mv';

async function fetchQQMusicPage() {
  try {
    const response = await axios.get(PAGE_URL, {
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Referer': 'https://y.qq.com/n/ryqq/mv'
      }
    });
    return response.data;
  } catch (error) {
    console.error('页面请求失败:', error.message);
    throw error;
  }
}

async function parseMVList(html) {
  const $ = cheerio.load(html);
  const mvList = [];

  // 假设MV信息在特定的DOM结构中
  $('#mv_list_item').each((index, element) => {
    const mvImg = $(element).find('img').attr('src');
    const mvTitle = $(element).find('.mv_title').text().trim();
    const mvAuthor = $(element).find('.mv_artist').text().trim();

    mvList.push([
      mvImg || '',
      mvTitle || '未知MV标题',
      mvAuthor || '未知作者'
    ]);
  });

  return mvList;
}

async function main() {
  const conn = await mysql.createConnection(dbConfig);

  try {
    // 创建表
    await conn.execute(`
      CREATE TABLE IF NOT EXISTS mvlist (
        ID INT AUTO_INCREMENT PRIMARY KEY,
        mvImg VARCHAR(500) NOT NULL,
        mvtitle VARCHAR(200) NOT NULL,
        mvauthor VARCHAR(100) NOT NULL
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    `);

    // 获取页面HTML
    const pageHtml = await fetchQQMusicPage();

    // 解析MV列表
    const mvList = await parseMVList(pageHtml);

    // 批量插入数据
    const [result] = await conn.query(
      'INSERT INTO mvlist (mvImg, mvtitle, mvauthor) VALUES ?',
      [mvList]
    );

    console.log(`成功插入 ${result.affectedRows} 条数据`);
  } catch (error) {
    console.error('运行出错:', error.message);
  } finally {
    await conn.end();
  }
}

main();
